//
//  SinaComposeTextView.swift
//  SinaWeibo
//
//  Created by 王朝阳 on 2016/11/6.
//  Copyright © 2016年 wangzhaoyang. All rights reserved.
//

import UIKit

class SinaComposeTextView: UITextView {
    
    //MARK: - 懒加载控件
    fileprivate lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.text = "为了更美好的明天而战..."
        label.font = UIFont.systemFont(ofSize: 13)
        label.textColor = UIColor.lightGray
        //设置多行显示
        label.numberOfLines = 0
        return label
    }()

    //声明属性供外界赋值
    var placeHolder: String? {
        didSet{
            placeHolderLabel.text = placeHolder
        }
    }
    //重写 font 属性,设置 label 的 font 属性
    override var font: UIFont? {
        didSet {
            if font != nil {
                placeHolderLabel.font = font!
            }
        }
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MARK: - 添加控件
    private func setupUI() {
//        backgroundColor = UIColor.red
        //添加控件并设置约束
        addSubview(placeHolderLabel)
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 6))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
        
        //MARK: - 监听文字的改变
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
    }
    
    @objc private func textChange() {
        //判断文本框中是否有内容
        placeHolderLabel.isHidden = hasText
    }
    deinit {
        //移除通知
        NotificationCenter.default.removeObserver(self)
    }
}
